package com.idlecode.panel;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.smallbun.screw.core.engine.EngineFileType;
import com.idlecode.bean.DataBaseEntity;
import com.idlecode.bean.DataSourceEntity;
import com.idlecode.bean.TableEntity;
import com.idlecode.component.MultiSelectComboBox;
import com.idlecode.config.GenDataSource;
import com.idlecode.manage.CodeFormatManage;
import com.idlecode.manage.DocumentManage;
import com.idlecode.service.*;
import com.idlecode.statics.CodeFormat;
import com.idlecode.statics.TemplateInfoStatic;
import com.idlecode.util.VcsUtil;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.table.JBTable;
import com.intellij.util.ui.WrapLayout;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: IdleCode
 * @description
 * @author: rongjuwei
 * @create: 2024-02-06 17:27
 **/
public class CodeGenerationPanel extends JPanel {
    private static List<TableEntity> tableList;
    private static List<DataBaseEntity> dataBaseList;
    // 创建表格模型
    private DefaultTableModel tableModel;
    private JTable table;
    private ComboBox<String> dataSourceComboBox;
    private ComboBox<String> dataBaseComboBox;
    private ComboBox<String> codeFormatComboBox;
    private JTextField tableNameField;
    private JRadioButton initGenRadioBtn;
    private JRadioButton updateBaseCodeRadioBtn;
    private JRadioButton updateAllCodeRadioBtn;
    private MultiSelectComboBox codeFileComboBox;


    private static String[] COLUMN_NAME = {"表名", "注释"};

    public CodeGenerationPanel(Project project) {
        List<DataSourceEntity> dataSourcesRows = DataSourceService.getInstance().getDataSources();
        //JPanel topJPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
        JPanel topJPanel = new JPanel(new WrapLayout(WrapLayout.LEFT));
        //调整
        topJPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 500));
        // 创建一个标签 JLabel 数据源实例
        JLabel dataSourceLabel = new JLabel("数据源：");
        // 添加标签到面板
        topJPanel.add(dataSourceLabel);
        // 创建一个下拉列表
        String[] dataSourceNames = getDataSourceNames();
        dataSourceComboBox = new ComboBox<>(dataSourceNames, 150);
        // 添加选择监听器
        dataSourceComboBox.addActionListener(e -> {
            boolean showDataBases = showDataBases();
            if (!showDataBases) {
                Messages.showMessageDialog("数据库连接失败！", "提示", Messages.getInformationIcon());
            }
        });
        // 添加下拉列表到面板
        topJPanel.add(dataSourceComboBox);

        //创建一个标签 JLabel 数据库实例
        JLabel dataBaseLabel = new JLabel("数据库：");
        // 添加标签到面板
        topJPanel.add(dataBaseLabel);

        dataBaseComboBox = new ComboBox<>(150);
        dataBaseComboBox.addActionListener(e -> {
            Object selectedItem = dataBaseComboBox.getSelectedItem();
            if (selectedItem != null) {
                if (!refreshTable()) {
                    Messages.showMessageDialog("数据库连接失败！", "异常", Messages.getErrorIcon());
                }
            }
        });
        // 添加下拉列表到面板
        topJPanel.add(dataBaseComboBox);

        JButton refreshDataSourceBtn = new JButton("刷新数据源");
        // 添加按钮点击事件的监听器
        refreshDataSourceBtn.addActionListener(e -> {
            String[] finalDataSourceNames = getDataSourceNames();
            dataSourceComboBox.setModel(new DefaultComboBoxModel<>(finalDataSourceNames));
            boolean showDataBases = showDataBases();
            if (showDataBases) {
                Messages.showMessageDialog("数据源刷新成功！", "提示", Messages.getInformationIcon());
            } else {
                Messages.showMessageDialog("数据源刷新成功！,但数据库连接失败！", "提示", Messages.getInformationIcon());
            }
        });
        topJPanel.add(refreshDataSourceBtn);
        tableNameField = new JTextField("请输入表名或注释");
        tableNameField.setColumns(13);
        tableNameField.setToolTipText("请输入表名或注释");
        // 添加文档监听器
        tableNameField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                // 当有文本插入时触发
                updateText();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                // 当有文本删除时触发
                updateText();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                // 当文本属性变化时触发（通常用于样式的变化，对于普通的文本框不太常用）
            }

            // 更新文本内容
            private void updateText() {
                String text = tableNameField.getText();
                if (StrUtil.isNotBlank(text) && !"请输入表名或注释".equals(text)) {
                    if (CollUtil.isNotEmpty(tableList)) {
                        String textLowerCase = text.toLowerCase();
                        String[] splitText = textLowerCase.split("\\|");
                        List<TableEntity> filterTables = new ArrayList<>();
                        for (String searchText : splitText) {
                            filterTables.addAll(tableList.stream()
                                    .filter(tableEntity -> (StrUtil.isBlank(tableEntity.getTableName()) ? false : tableEntity.getTableName().toLowerCase().contains(searchText))
                                            || (StrUtil.isBlank(tableEntity.getTableComment()) ? false : tableEntity.getTableComment().toLowerCase().contains(searchText))
                                    ).collect(Collectors.toList()));
                        }
                        //去重
                        if (CollUtil.isNotEmpty(filterTables)) {
                            filterTables = filterTables.stream()
                                    .collect(Collectors.toMap(
                                            TableEntity::getTableName,  // 使用 name 作为唯一键
                                            p -> p,           // 保留整个对象
                                            (existing, replacement) -> existing  // 当有重复的 name 时，保留第一个
                                    ))
                                    .values()
                                    .stream()
                                    .collect(Collectors.toList());
                        }
                        clearData(tableModel);
                        for (TableEntity tableEntity : filterTables) {
                            // 添加数据行
                            tableModel.addRow(new Object[]{tableEntity.getTableName(), tableEntity.getTableComment()});
                            // 调整 JTable 的首选大小
                            table.setPreferredScrollableViewportSize(table.getPreferredSize());
                            // 通知父容器重新布局
                            table.revalidate();
                        }
                        updateColumnName(filterTables);
                    } else {
                        clearData(tableModel);
                        updateColumnName(tableList);
                    }
                } else {
                    if (CollUtil.isNotEmpty(tableList)) {
                        clearData(tableModel);
                        for (TableEntity tableEntity : tableList) {
                            // 添加数据行
                            tableModel.addRow(new Object[]{tableEntity.getTableName(), tableEntity.getTableComment()});
                            // 调整 JTable 的首选大小
                            table.setPreferredScrollableViewportSize(table.getPreferredSize());
                            // 通知父容器重新布局
                            table.revalidate();
                        }
                    } else {
                        clearData(tableModel);
                    }
                    updateColumnName(tableList);
                }
            }
        });

        // 设置提示文本颜色为灰色
        tableNameField.setForeground(Color.GRAY);

        // 添加焦点监听器
        tableNameField.addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent e) {
                if (tableNameField.getText().contains("请输入表名或注释")) {
                    tableNameField.setText("");
                    // 获取当前主题
                    EditorColorsScheme currentScheme = EditorColorsManager.getInstance().getGlobalScheme();
                    // 获取文本前景色
                    Color textColor = currentScheme.getDefaultForeground();
                    tableNameField.setForeground(textColor);
                }
            }

            @Override
            public void focusLost(FocusEvent e) {
                if (tableNameField.getText().isEmpty()) {
                    tableNameField.setForeground(Color.GRAY);
                    tableNameField.setText("请输入表名或注释");
                }
            }
        });
        topJPanel.add(tableNameField);
        JButton syncBtn = new JButton("同步表");
        // 添加按钮点击事件的监听器
        syncBtn.addActionListener(e -> {
            if (refreshTable()) {
                Messages.showMessageDialog("表同步成功！", "提示", Messages.getInformationIcon());
            } else {
                Messages.showMessageDialog("数据库连接失败！", "异常", Messages.getErrorIcon());
            }
        });
        topJPanel.add(syncBtn);

        //生成文件类型数组
        final List<String> options = TemplateInfoStatic.getNames();
        codeFileComboBox = new MultiSelectComboBox(options);
        codeFileComboBox.setSelectedItems(options);
        topJPanel.add(codeFileComboBox);

        //单选按钮
        initGenRadioBtn = new JRadioButton("初始化", true);
        initGenRadioBtn.setToolTipText("初始化代码会生成所有代码文件");
        initGenRadioBtn.addActionListener(e -> {
            if (initGenRadioBtn.isSelected()) {
                List<String> selectedOptions = options;
                codeFileComboBox.setSelectedItems(selectedOptions);
            }
        });
        updateBaseCodeRadioBtn = new JRadioButton("更新基础代码", false);
        updateBaseCodeRadioBtn.setToolTipText("只更新BaseEntity.java和BaseMapper.xml");
        updateBaseCodeRadioBtn.addActionListener(e -> {
            if (updateBaseCodeRadioBtn.isSelected()) {
                List<String> selectedOptions = CollUtil.newArrayList("BaseEntity.java", "BaseMapper.xml");
                codeFileComboBox.setSelectedItems(selectedOptions);
            }
        });
        updateAllCodeRadioBtn = new JRadioButton("更新完整代码", false);
        updateAllCodeRadioBtn.setToolTipText("更新BaseEntity.java、BaseMapper.xml、Mapper.xml");
        updateAllCodeRadioBtn.addActionListener(e -> {
            if (updateAllCodeRadioBtn.isSelected()) {
                List<String> selectedOptions = CollUtil.newArrayList("BaseEntity.java", "BaseMapper.xml", "Mapper.xml");
                codeFileComboBox.setSelectedItems(selectedOptions);
            }
        });

        ButtonGroup group = new ButtonGroup();
        group.add(initGenRadioBtn);
        group.add(updateBaseCodeRadioBtn);
        group.add(updateAllCodeRadioBtn);

        topJPanel.add(initGenRadioBtn);
        topJPanel.add(updateBaseCodeRadioBtn);
        topJPanel.add(updateAllCodeRadioBtn);
        // 添加竖直分隔线
        addSeparator(topJPanel);
        //创建一个标签 JLabel 数据库实例
        JLabel codeFormatLabel = new JLabel("代码格式：");
        // 添加标签到面板
        topJPanel.add(codeFormatLabel);
        codeFormatComboBox = new ComboBox<>(100);
        CodeFormat.getCodeFormats().keySet().stream().forEach(formatName -> codeFormatComboBox.addItem(formatName));
        codeFormatComboBox.setSelectedIndex(0);
        // 添加下拉列表到面板
        topJPanel.add(codeFormatComboBox);

        // 创建问号图标标签
        JLabel helpLabel = new JLabel();
        // 加载资源图片
        URL imageUrl = getClass().getResource("/picture/unknown_factor.png");
        helpLabel.setIcon(new ImageIcon(imageUrl));
        helpLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        topJPanel.add(helpLabel);

        // 为问号按钮添加点击事件
        helpLabel.addMouseListener(
                new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        CodeFormatManage.showCodeFormatHelp(topJPanel);
                    }
                });

        // 添加空白组件
        JLabel spacer = new JLabel("         "); // 空白的 JLabel，可以通过设置大小来调整空白的大小

        topJPanel.add(spacer);

        JButton genBtn = new JButton("生成代码");
        // 设置按钮的背景颜色
        genBtn.setBackground(Color.PINK);
        // 生成代码按钮点击事件的监听器
        genBtn.addActionListener(e -> {
            //获取选中的行
            int[] selectedRows = table.getSelectedRows();
            if (selectedRows == null || selectedRows.length <= 0) {
                Messages.showMessageDialog("未选中任何表！", "警告", Messages.getWarningIcon());
                return;
            }
            // 通过选中行索引获取该行数据
            List<String> tableNames = new ArrayList<>();
            for (int selectedRow : selectedRows) {
                String tableName = table.getValueAt(selectedRow, 0).toString();
                tableNames.add(tableName);
            }
            //获取选中的数据源
            int selectedIndex = dataSourceComboBox.getSelectedIndex();
            if (selectedIndex < 0) {
                Messages.showMessageDialog("未选中任何数据源！", "警告", Messages.getWarningIcon());
                return;
            }
            DataSourceEntity dataSourceEntity = dataSourcesRows.get(selectedIndex);

            //获取选择的数据库
            String dataBaseSelectedItem = StrUtil.utf8Str(dataBaseComboBox.getSelectedItem());
            if (StrUtil.isBlank(dataBaseSelectedItem)) {
                Messages.showMessageDialog("未选中任何数据库！", "警告", Messages.getWarningIcon());
                return;
            }

            //获取需要生成的文件
            List<String> selectedGenFileItems = codeFileComboBox.getSelectedItems();
            if (CollUtil.isEmpty(selectedGenFileItems)) {
                Messages.showMessageDialog("请选择要生成的文件类型！", "警告", Messages.getWarningIcon());
                return;
            }

            String codeFormatItem = StrUtil.utf8Str(codeFormatComboBox.getSelectedItem());
            if (StrUtil.isBlank(codeFormatItem)) {
                Messages.showMessageDialog("请选择要生成的代码格式！", "警告", Messages.getWarningIcon());
                return;
            }

            try {
                GeneratorService.generateCode(project,
                        dataSourceEntity,
                        tableNames,
                        dataBaseSelectedItem,
                        selectedGenFileItems,
                        codeFormatItem);
                //刷新文件管理器
                VirtualFileManager.getInstance().refreshWithoutFileWatcher(true);
                //VCS 刷新
                VcsUtil.refreshVcs(project);
                Messages.showMessageDialog("代码生成成功！", "提示", Messages.getInformationIcon());
            } catch (Exception ex) {
                Messages.showMessageDialog(ex.getMessage(), "异常", Messages.getErrorIcon());
            }
        });
        topJPanel.add(genBtn);

        JButton genTableStructureDetailBtn = new JButton("导出表结构详情");
        // 设置按钮的背景颜色
        genTableStructureDetailBtn.setBackground(Color.GRAY);
        // 生成表结构详情按钮点击事件的监听器
        genTableStructureDetailBtn.addActionListener(e -> {
            List<String> tableNames = new ArrayList<>();
            //获取选中的行
            int[] selectedRows = table.getSelectedRows();
            if (selectedRows != null && selectedRows.length > 0) {
                // 通过选中行索引获取该行数据
                for (int selectedRow : selectedRows) {
                    String tableName = table.getValueAt(selectedRow, 0).toString();
                    tableNames.add(tableName);
                }
            }

            //获取选中的数据源
            int selectedIndex = dataSourceComboBox.getSelectedIndex();
            if (selectedIndex < 0) {
                Messages.showMessageDialog("未选中任何数据源！", "警告", Messages.getWarningIcon());
                return;
            }
            DataSourceEntity dataSourceEntity = dataSourcesRows.get(selectedIndex);

            //获取选择的数据库
            String dataBaseSelectedItem = StrUtil.utf8Str(dataBaseComboBox.getSelectedItem());
            if (StrUtil.isBlank(dataBaseSelectedItem)) {
                Messages.showMessageDialog("未选中任何数据库！", "警告", Messages.getWarningIcon());
                return;
            }

            // 创建文件选择器描述符，只允许选择文件夹
            FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false);
            descriptor.setTitle("选择生成文件的位置");
            descriptor.setDescription("请选择一个文件夹来生成文件");

            // 获取桌面路径
            File desktop = new File(System.getProperty("user.home"), "Desktop");
            VirtualFile desktopVirtualFile = VfsUtil.findFileByIoFile(desktop, true);

            // 弹出文件选择对话框
            VirtualFile file = FileChooser.chooseFile(descriptor, project, desktopVirtualFile);
            if (file == null) {
                return;
            }
            // 选择的文件夹路径
            String folderPath = file.getPath();

            try {
                GeneratorService.generateTableStructureDetail(project, dataSourceEntity, tableNames, dataBaseSelectedItem, folderPath);
            } catch (Exception ex) {
                Messages.showMessageDialog(ex.getMessage(), "异常", Messages.getErrorIcon());
            }

        });
        topJPanel.add(genTableStructureDetailBtn);

        JButton documentGenerationBtn = new JButton("导出数据库文档");
        // 设置按钮的背景颜色
        documentGenerationBtn.setBackground(Color.GRAY);
        // 生成表结构详情按钮点击事件的监听器
        documentGenerationBtn.addActionListener(e -> {
            List<String> tableNames = new ArrayList<>();
            //获取选中的行
            int[] selectedRows = table.getSelectedRows();
            if (selectedRows != null && selectedRows.length > 0) {
                // 通过选中行索引获取该行数据
                for (int selectedRow : selectedRows) {
                    String tableName = table.getValueAt(selectedRow, 0).toString();
                    tableNames.add(tableName);
                }
            }

            //获取选中的数据源
            int selectedIndex = dataSourceComboBox.getSelectedIndex();
            if (selectedIndex < 0) {
                Messages.showMessageDialog("未选中任何数据源！", "警告", Messages.getWarningIcon());
                return;
            }
            DataSourceEntity dataSourceEntity = dataSourcesRows.get(selectedIndex);

            //获取选择的数据库
            String dataBaseSelectedItem = StrUtil.utf8Str(dataBaseComboBox.getSelectedItem());
            if (StrUtil.isBlank(dataBaseSelectedItem)) {
                Messages.showMessageDialog("未选中任何数据库！", "警告", Messages.getWarningIcon());
                return;
            }

            Map<String, Object> condition = new HashMap<>();
            DocumentManage documentManage = new DocumentManage(condition);
            boolean ok = documentManage.showAndGet();
            if (!ok) {
                return;
            }

            // 创建文件选择器描述符，只允许选择文件夹
            FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false);
            descriptor.setTitle("选择生成文件的位置");
            descriptor.setDescription("请选择一个文件夹来生成文件");

            // 获取桌面路径
            File desktop = new File(System.getProperty("user.home"), "Desktop");
            VirtualFile desktopVirtualFile = VfsUtil.findFileByIoFile(desktop, true);

            // 弹出文件选择对话框
            VirtualFile file = FileChooser.chooseFile(descriptor, project, desktopVirtualFile);
            if (file == null) {
                return;
            }
            // 选择的文件夹路径
            String folderPath = file.getPath();

            try {
                GeneratorService.documentGeneration(
                        project,
                        dataSourceEntity,
                        dataBaseSelectedItem,
                        tableNames,
                        folderPath,
                        (EngineFileType) condition.get("fileType"),
                        (String) condition.get("version"),
                        (String) condition.get("description")
                );
            } catch (Exception ex) {
                ex.printStackTrace();
                Messages.showMessageDialog(ex.getMessage(), "异常", Messages.getErrorIcon());
            }
        });
        topJPanel.add(documentGenerationBtn);

        //列表显示
        JPanel bottomJPanel = new JPanel(new BorderLayout());
        tableModel = new DefaultTableModel();

        // 添加列名
        for (String columnName : COLUMN_NAME) {
            tableModel.addColumn(columnName);
        }

        // 创建表格
        table = new JBTable(tableModel);
        // 设置 JTable 的自动调整列宽度模式为 AUTO_RESIZE_SUBSEQUENT_COLUMNS
        // 这样可以确保在调整列宽度时，只调整之后的列宽度，而不会影响之前的列
        table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);

        boolean showDataBases = showDataBases();
        if (!showDataBases) {
            Messages.showMessageDialog("数据库连接失败", "异常", Messages.getErrorIcon());
        }

        // 设置表头居中
        DefaultTableCellRenderer headerRenderer = new DefaultTableCellRenderer();
        headerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
        table.getTableHeader().setDefaultRenderer(headerRenderer);
        // 将表格放置在滚动窗格中
        JScrollPane scrollPane = new JBScrollPane(table);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        bottomJPanel.add(scrollPane);

        // 垂直排列
        setLayout(new BorderLayout());
        add(topJPanel, BorderLayout.NORTH);
        add(bottomJPanel, BorderLayout.CENTER);
        addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                int jpWidth = getWidth();
                table.setPreferredScrollableViewportSize(new Dimension(jpWidth, table.getPreferredScrollableViewportSize().height));
                // 设置列宽度比例
                setColumnProportionalWidth(table, 0, 0.4, jpWidth);
                setColumnProportionalWidth(table, 1, 0.6, jpWidth);

            }
        });
    }

    // 创建一个下拉列表
    @Nullable
    private static String[] getDataSourceNames() {
        List<DataSourceEntity> dataSources = DataSourceService.getInstance().getDataSources();
        String[] options = null;
        if (dataSources != null) {
            List<String> connNames = dataSources.stream().map(DataSourceEntity::getConnName).collect(Collectors.toList());
            options = connNames.toArray(new String[0]);
        }
        return options;
    }

    // 设置列宽度比例
    private static void setColumnProportionalWidth(JTable table, int columnIndex, double proportion, int jpWidth) {
        TableColumn column = table.getColumnModel().getColumn(columnIndex);
        int width = (int) (proportion * jpWidth);
        column.setPreferredWidth(width);
    }

    // 清除表格模型中的数据
    private static void clearData(DefaultTableModel model) {
        int rowCount = model.getRowCount();
        for (int i = rowCount - 1; i >= 0; i--) {
            model.removeRow(i);
        }
    }

    public boolean showDataBases() {
        clearData(tableModel);
        dataBaseComboBox.removeAllItems();
        //获取所有数据源
        List<DataSourceEntity> dataSourcesRows = DataSourceService.getInstance().getDataSources();
        if (CollUtil.isNotEmpty(dataSourcesRows)) {
            //获取选中的数据源
            int selectedIndex = dataSourceComboBox.getSelectedIndex();
            DataSourceEntity dataSourceEntity = dataSourcesRows.get(selectedIndex);
            GenDataSource genDataSource = null;
            try {
                genDataSource = new GenDataSource(dataSourceEntity);
                if (genDataSource.getConnection() == null) {
                    return false;
                }
                dataBaseList = DataBaseService.getDataBaseList(genDataSource);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (genDataSource.getConnection() != null) {
                        genDataSource.getConnection().close();
                    }
                } catch (SQLException ex) {
                    Messages.showMessageDialog("连接关闭失败！", "异常", Messages.getErrorIcon());
                }
            }

            for (DataBaseEntity dataBaseEntity : dataBaseList) {
                dataBaseComboBox.addItem(dataBaseEntity.getOwner());
            }
        }
        return true;
    }

    public boolean refreshTable() {
        clearData(tableModel);
        List<DataSourceEntity> dataSourcesRows = DataSourceService.getInstance().getDataSources();
        if (CollUtil.isNotEmpty(dataSourcesRows)) {
            //获取选择的数据源
            int dataSourceSelectedIndex = dataSourceComboBox.getSelectedIndex();
            DataSourceEntity dataSourceEntity = dataSourcesRows.get(dataSourceSelectedIndex);
            GenDataSource genDataSource = null;
            try {
                //获取选择的数据库
                String dataBaseSelectedItem = String.valueOf(dataBaseComboBox.getSelectedItem());
                genDataSource = new GenDataSource(dataSourceEntity, dataBaseSelectedItem);
                if (genDataSource.getConnection() == null) {
                    return false;
                }

                if (StrUtil.isNotBlank(dataBaseSelectedItem)) {
                    String codeFormatName = CodeFormatService.getInstance().getCodeFormatName(dataSourceEntity.getDsId(), dataBaseSelectedItem);
                    codeFormatComboBox.setItem(codeFormatName);
                    tableList = TableService.getTableList(genDataSource, dataBaseSelectedItem);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (genDataSource.getConnection() != null) {
                        genDataSource.getConnection().close();
                    }
                } catch (SQLException ex) {
                    Messages.showMessageDialog("连接关闭失败！", "异常", Messages.getErrorIcon());
                }
            }

            String text = tableNameField.getText();
            if (StrUtil.isNotBlank(text) && !"请输入表名或注释".equals(text)) {
                if (CollUtil.isNotEmpty(tableList)) {
                    String textLowerCase = text.toLowerCase();
                    String[] splitText = textLowerCase.split("\\|");
                    List<TableEntity> filterTables = new ArrayList<>();
                    for (String searchText : splitText) {
                        filterTables.addAll(tableList.stream()
                                .filter(tableEntity -> (StrUtil.isBlank(tableEntity.getTableName()) ? false : tableEntity.getTableName().toLowerCase().contains(searchText))
                                        || (StrUtil.isBlank(tableEntity.getTableComment()) ? false : tableEntity.getTableComment().toLowerCase().contains(searchText))
                                ).collect(Collectors.toList()));
                    }
                    //去重
                    if (CollUtil.isNotEmpty(filterTables)) {
                        filterTables = filterTables.stream()
                                .collect(Collectors.toMap(
                                        TableEntity::getTableName,  // 使用 name 作为唯一键
                                        p -> p,           // 保留整个对象
                                        (existing, replacement) -> existing  // 当有重复的 name 时，保留第一个
                                ))
                                .values()
                                .stream()
                                .collect(Collectors.toList());
                    }
                    for (TableEntity tableEntity : filterTables) {
                        // 添加数据行
                        tableModel.addRow(new Object[]{tableEntity.getTableName(), tableEntity.getTableComment()});
                    }
                    // 调整 JTable 的首选大小
                    table.setPreferredScrollableViewportSize(table.getPreferredSize());
                    // 通知父容器重新布局
                    table.revalidate();
                    updateColumnName(filterTables);
                } else {
                    updateColumnName(tableList);
                }
            } else {
                if (CollUtil.isNotEmpty(tableList)) {
                    for (TableEntity tableEntity : tableList) {
                        // 添加数据行
                        tableModel.addRow(new Object[]{tableEntity.getTableName(), tableEntity.getTableComment()});
                    }
                    // 调整 JTable 的首选大小
                    table.setPreferredScrollableViewportSize(table.getPreferredSize());
                    // 通知父容器重新布局
                    table.revalidate();
                }
                updateColumnName(tableList);
            }
        }
        return true;
    }

    private void updateColumnName(List<TableEntity> tableEntityList) {
        // 修改列名
        String[] newColumnNames = new String[COLUMN_NAME.length];
        // 添加列名
        for (int i = 0; i < COLUMN_NAME.length; i++) {
            if (i == 0) {
                newColumnNames[i] = COLUMN_NAME[i] + "(" + (tableEntityList == null ? "0" : tableEntityList.size()) + ")";
            } else {
                newColumnNames[i] = COLUMN_NAME[i];
            }
        }
        tableModel.setColumnIdentifiers(newColumnNames);
    }

    // 添加竖直分隔线的方法
    private void addSeparator(JPanel jPanel) {
        JPanel separator = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setColor(Color.GRAY); // 设置竖线颜色
                g2d.setStroke(new BasicStroke(2)); // 设置竖线的宽度
                int x = getWidth() / 2;
                int y1 = 0; // 设置竖线起始位置
                int y2 = getHeight() + 15; // 设置竖线结束位置
                g2d.drawLine(x, y1, x, y2); // 绘制竖线
            }
        };
        Dimension size = new Dimension(2, getHeight() + 15); // 设置竖线的大小
        separator.setPreferredSize(size);
        jPanel.add(separator);
    }
}
